#include "NetToolKits.h"

IocpClientPool::IocpClientPool(int maxPoolSize){
	_maxPoolSize = maxPoolSize;
	_iocpClientQueue = new queue < IocpClient* > ;
}

IocpClientPool::~IocpClientPool(){
	delete _iocpClientQueue;
	_iocpClientQueue = NULL;
}

void IocpClientPool::_extendpool(){
	if (_iocpClientQueue->size() < _maxPoolSize){
		for (int i = 0; i < 100; ++i){
			_iocpClientQueue->push(new IocpClient());
		}
	}
}

IocpClient* IocpClientPool::popUp(){
	WaitForSingleObject(_poolMutex, INFINITE);
	if (_iocpClientQueue->size() <= 0){
		_extendpool();
	}
	IocpClient * ret = _iocpClientQueue->front();
	_iocpClientQueue->pop();
	ReleaseMutex(_poolMutex);
	return ret;
}

void IocpClientPool::pushBack(IocpClient* iocpClient){
	if (iocpClient != NULL){
		if (iocpClient->connectSocket != 0){
			closesocket(iocpClient->connectSocket);
			iocpClient->connectSocket = 0;
		}
		_iocpClientQueue->push(iocpClient);
	}
}

void IocpClientPool::destroyPool(){
	while (_iocpClientQueue->size() > 0){
		delete _iocpClientQueue->front();
		_iocpClientQueue->pop();
	}
}